package com.etc.reflectdemo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class TestPerson {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        //得到Person.class
        Class<Person> personClass = Person.class;

        // 1 getDeclaredFields => Field[]
        System.out.println("*************getDeclaredFields*************");
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field f : declaredFields) {
            //我们Filed类
            System.out.println(f.getName() + " " + f.getModifiers());
        }

        System.out.println("*************getFields*************");
        Field[] fields = personClass.getFields();
        for (Field f : fields) {
            //我们Filed类
            System.out.println(f.getName() + ": " + f.getModifiers());
        }

        System.out.println("*************getDeclaredField,并给私有的属性赋值*************");
        //可以尝试给某个属性赋值
        Field fieldid = personClass.getDeclaredField("id");
        //需要创建Person类型的对象
//        Person person = personClass.newInstance();
        Person person1 = personClass.getConstructor().newInstance();
        fieldid.setAccessible(true);
        //给id这个属性赋值
        fieldid.set(person1, 100);

        System.out.println(person1);


    }
}
